import { onMounted, onUnmounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import { hookResult } from './bindResult';
import {
  createModeModalBinder,
  IModalProps,
  ModeModalResult,
} from './useModeModalBinder';

export type MyModes =
  | readonly ['detail', 'add', 'edit']
  | readonly ['detail', 'add', 'edit', ...string[]];

export type DetailDrawerBinderProps<T extends MyModes> = IModalProps<T> & {
  modes?: T;
  delete?: boolean;
  deleteText?: string;
  deleteApi?: () => Promise<any>;
  modalName?: string;
};

export default function useDetailDrawerBinder<T extends MyModes>(
  props: DetailDrawerBinderProps<T>
): ModeModalResult<T> {
  const {
    modes = ['detail', 'add', 'edit'] as const,
    modalName,
    deleteApi,
    deleteText,
    ...otherProps
  } = props;

  const [modal, bindProps] = createModeModalBinder({
    modes: modes as T,
    ...otherProps,
  });

  const onDelete = () => {
    if (deleteApi) {
      return deleteApi().then((res) => {
        // @ts-ignore
        modal.triggerSuccess('detail', null);
        modal.triggerCancel();
        return res;
      });
    }
    return Promise.resolve();
  };

  const onEdit = () => {
    // @ts-ignore
    modal.changeMode('edit');
  };

  const onSave = () => {
    modal.triggerOk();
  };

  const onSuccess = (mode: any) => {
    if (mode === 'add') {
      Message.success('新建成功');
    }
    if (mode === 'edit') {
      Message.success('编辑成功');
    }
  };

  onMounted(() => {
    modal.expose.registerSuccess(onSuccess);
  });

  onUnmounted(() => {
    modal.expose.unregisterSuccess(onSuccess);
  });

  return hookResult(modal, {
    onDelete,
    onEdit,
    onSave,
    modalName,
    deleteText,
    ...bindProps,
  });
}
